package utils

import (
	"context"
	"fmt"
	"log"
	"os"
	"time"

	"github.com/go-redis/redis/v8"
	"github.com/spf13/viper"
	"gorm.io/driver/mysql"
	"gorm.io/gorm"
	"gorm.io/gorm/logger"
)

var DB *gorm.DB
var RDB *redis.Client
var ctx = context.Background()

func InitConfig() {
	viper.SetConfigName("app")
	viper.AddConfigPath("config")
	err := viper.ReadInConfig()
	if err != nil {
		fmt.Println(err)
	}
	//fmt.Println("config app:", viper.Get("mysql"))
	fmt.Println("configed ...")
}

func InitMysql() {
	newLogger := logger.New(log.New(os.Stdout, "\n", log.LstdFlags), logger.Config{
		SlowThreshold: time.Second,
		LogLevel:      logger.Info,
		Colorful:      true,
	})
	DB, _ = gorm.Open(mysql.Open(viper.GetString("mysql.dns")), &gorm.Config{Logger: newLogger})
	fmt.Println("mysql configed ...")

}

func InitRedis() {
	RDB = redis.NewClient(&redis.Options{
		Addr:     viper.GetString("redis.addr"),
		Password: viper.GetString("redis.password"),
		DB:       viper.GetInt("redis.DB"),
	})
	fmt.Println("redis configed ...")
}

const (
	PublishKey = "websocket"
)

func Publish(ctx context.Context, channel string, message interface{}) error {
	err := RDB.Publish(ctx, channel, message).Err()
	fmt.Println("Publish ...", message)
	if err != nil {
		fmt.Println(err)
		return err
	}
	fmt.Println("Publish ...", message)
	return err
}

// 订阅消息
func Subscribe(ctx context.Context, channel string) (string, error) {
	sub := RDB.Subscribe(ctx, channel)
	fmt.Println("Subscribe ...", ctx)

	msg, err := sub.ReceiveMessage(ctx)
	if err != nil {
		fmt.Println(err)
		return "", err
	}
	fmt.Println("Subscribe ...", msg.Payload)

	return msg.Payload, err
}
